package com.pz.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.pz.gulimall.product.entity.SkuInfoEntity;
import com.pz.gulimall.product.service.SkuInfoService;
import com.pz.gulimall.product.vo.req.SkuImagesReqVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pz.gulimall.common.utils.PageUtils;
import com.pz.gulimall.common.utils.Query;

import com.pz.gulimall.product.dao.SkuImagesDao;
import com.pz.gulimall.product.entity.SkuImagesEntity;
import com.pz.gulimall.product.service.SkuImagesService;

import javax.annotation.Resource;


@Service("skuImagesService")
public class SkuImagesServiceImpl extends ServiceImpl<SkuImagesDao, SkuImagesEntity> implements SkuImagesService {
    @Autowired
    private SkuInfoService skuInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String skuId = (String) params.get("skuId");
        QueryWrapper<SkuImagesEntity> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(skuId)){
            queryWrapper.eq("sku_id", skuId);
        }
        IPage<SkuImagesEntity> page = this.page(
                new Query<SkuImagesEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void updateById(SkuImagesReqVo skuImagesVo) {
        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
        BeanUtils.copyProperties(skuImagesVo, skuImagesEntity);
        if(skuImagesEntity.getDefaultImg() == 1){
            skuInfoService.update(new UpdateWrapper<SkuInfoEntity>()
                    .set("sku_default_img", skuImagesEntity.getImgUrl())
                    .eq("sku_id", skuImagesEntity.getSkuId())
            );
            //更新ES数据
            skuInfoService.updateSkuEsModel(skuInfoService.getById(skuImagesEntity.getSkuId()).getSpuId());
        }
        this.updateById(skuImagesEntity);

    }

}